const mongoose = require("mongoose");

const dbUrl = `mongodb://127.0.0.1:27017` // 数据库地址
const dbName = `hiflydb` // 数据库名称

const address = `${dbUrl}/${dbName}`
mongoose.connect(address);

// mongoose.connection.on("open", () => {
//     console.log("连接打开")
// })

// 断线重连，回调 once 只执行一次，on 每次都执行。
mongoose.connection.once("open", () => {
    const str = "连接打开"
    console.log('%c 姓名: %s', 'color: #fff; background-color: blue; font-size: 20px;', str)

    // 创建文档结构对象, 作用:约束集合
    let BookSchema = new mongoose.Schema({
        name: {
            type: String,
            require: true,
            default: "ecg",
            enum: ["ecg", "重症", "ICU"],
            unique: true, // 唯一值
        },
        author: String,
        price: Number,
        test: mongoose.Types.Subdocument
    })

    // 创建模型对象, 对文档操作的封装对象，CRUD,  books为集合名称， 没有自动创建，有了往里面添加。
    let BookModel = mongoose.model('books', BookSchema);

    // 调用模型方法，CRUD
    BookModel.create({
        name: "hifly up",
        author: "ymq",
        price: 200,    
    }).then(res => {
        console.log(res);
    }, err => {
        console.log("插入异常", err);
    })
})

mongoose.connection.on("close", () => {
    console.log("连接关闭")
})

mongoose.connection.on("error", () => {
    console.log("连接异常")
})
